package role_service

import (
	"errors"
	"starry_sky/internal/dal"
	"starry_sky/internal/dal/role-dal"
	"starry_sky/internal/dto/role_dto"
	"starry_sky/internal/model"
	"starry_sky/internal/tools/logger"
)

func CreateRole(role *model.Role) error {
	var hasCode int64
	err := dal.JudgmentRepetition[model.Role](&hasCode, map[string]any{"code": role.Code}, role.ID)
	if logger.HasError(err) {
		return errors.New("查询角色编码是否重复失败")
	}
	if hasCode > 0 {
		return errors.New("角色编码已存在")
	}
	err = dal.Insert(role)
	if logger.HasError(err) {
		return errors.New("新增角色失败")
	}
	return nil
}

func UpdateRole(role *model.Role) error {
	var hasCode int64
	err := dal.JudgmentRepetition[model.Role](&hasCode, map[string]any{"code": role.Code}, role.ID)
	if logger.HasError(err) {
		return errors.New("查询角色编码是否重复失败")
	}
	if hasCode > 0 {
		return errors.New("角色编码已存在")
	}
	err = dal.Save(role)
	if logger.HasError(err) {
		return errors.New("更新角色失败")
	}
	return nil
}

// BindRoleAndPermission 绑定角色权限
func BindRoleAndPermission(bindRoleAndPermission *role_dto.BindRoleAndPermission) error {
	var role model.Role
	role.ID = bindRoleAndPermission.RoleId
	err := dal.FindById(&role)
	if logger.HasError(err) {
		return errors.New("查询角色失败")
	}
	var permissions []model.Permission
	for _, permissionId := range bindRoleAndPermission.MenuIds {
		var permission model.Permission
		permission.ID = permissionId
		err := dal.FindById(&permission)
		if logger.HasError(err) {
			return errors.New("查询权限失败")
		}
		permissions = append(permissions, permission)
	}
	tx := dal.TransactionBegin()
	err = role_dal.ClearRoleAndPermission(tx, &role)
	if logger.HasError(err) {
		err := dal.TransactionRollback(tx)
		if logger.HasError(err) {
			logger.SysErrorF("事务回滚失败")
		}
		return errors.New("清除角色权限失败")
	}
	err = role_dal.BindRoleAndPermission(tx, &role, permissions)
	if logger.HasError(err) {
		err := dal.TransactionRollback(tx)
		if logger.HasError(err) {
			logger.SysErrorF("事务回滚失败")
		}
		return errors.New("绑定角色权限失败")
	}
	err = dal.TransactionCommit(tx)
	return nil
}
